package com.liry.security.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.liry.security.util.RsaUtil;
import java.io.IOException;
import java.io.InputStream;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * 自定义json认证
 *
 * @author ALI
 * @since 2023/6/7
 */
@Slf4j
public class CustomUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private static String decondePassword(String password) throws NoSuchAlgorithmException, InvalidKeySpecException {
        byte[] decode = Base64.getDecoder().decode(password.getBytes());
        return new String(RsaUtil.decrypt(SecurityWebConfig.privateKey, decode));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        try (InputStream inputStream = request.getInputStream()) {
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, String> loginRequest = objectMapper.readValue(inputStream, Map.class);
            String username = loginRequest.get(super.getUsernameParameter());
            String password = loginRequest.get(super.getPasswordParameter());
            try {
                password = decondePassword(password);
            } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
                log.error("密码解密失败！！！！", e);
                password = null;
            }
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            // 使用 AuthenticationManager 进行身份验证
            return this.getAuthenticationManager().authenticate(authenticationToken);
        } catch (IOException e) {
            throw new BadCredentialsException(e.getMessage());
        }
    }
}
